//
//  AuctionSearchVC.m
//  MyNewProject
//
//  Created by 王春辉 on 2020/1/4.
//  Copyright © 2020年 sun. All rights reserved.
//

#import "AuctionSearchVC.h"
#import "AuctionCollectionViewCell.h"
#import "AuctionProductDetailVC.h"

#pragma mark -- mark 数据模型
#import "AuctionSellModel.h"

#define MARGIN 15.0

@interface AuctionSearchVC ()<UICollectionViewDelegate, UICollectionViewDataSource, UITextFieldDelegate> {
    int _page;
    BOOL _firstLoad;
}
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UITextField *textField;

@property (nonatomic, strong) NSArray <AuctionSellDataModel *>* dataArray;

/// 搜索关键字
@property (nonatomic, copy) NSString *searchKey;
@property (nonatomic, copy) void(^countDownEndBlock)(void);
@end
static NSString *const identifier = @"cell_identifier";
@implementation AuctionSearchVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = SKColorWithHex(0xF7F7F7);
    self.gk_navigationBar.hidden = true;
    _firstLoad = true;
    [self initBlock];
    [self initContentViews];
}

- (void)initContentViews {
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = [UIColor whiteColor];
    view.layer.masksToBounds = true;
    view.layer.cornerRadius = 4.0f;
    [self.view addSubview:view];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button addTarget:self action:@selector(searchButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [button setImage:SKIMAGE_NAMED(@"shop_search_btn_img") forState:UIControlStateNormal];
    [view addSubview:button];
    
    UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [cancelButton setTitle:@"取消" forState:UIControlStateNormal];
    cancelButton.titleLabel.font = SKFONT_SIZE(16);
    [cancelButton setTitleColor:SKColorWithHex(0x333333) forState:UIControlStateNormal];
    [cancelButton addTarget:self action:@selector(cancelButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:cancelButton];
    [view addSubview:self.textField];
    
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.top.mas_offset(SKStatusBar_Height + 12);
        make.right.mas_equalTo(cancelButton.mas_left).mas_offset(-15);
        make.height.mas_equalTo(42);
    }];
    
    [cancelButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_offset(-15);
        make.centerY.mas_equalTo(view).mas_offset(0);
        make.size.mas_equalTo(CGSizeMake(40, 16));
    }];
    
    [button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.size.mas_equalTo(CGSizeMake(20, 20));
        make.centerY.mas_offset(0);
    }];
    
    [self.textField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(button.mas_right).mas_offset(10);
        make.centerY.mas_offset(0);
        make.right.mas_offset(-10);
    }];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(view.mas_bottom).mas_offset(10);
        make.left.right.mas_offset(0);
        make.bottom.mas_offset(-SKBottomSafe_Height);
    }];
    
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(requestData)];
    self.collectionView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(requstMoreData)];
}

#pragma mark -- mark 懒加载
- (UICollectionView *)collectionView {
    if (!_collectionView) {
        CGFloat centerMargin = 5.0; // 中间边距
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        CGFloat item_w = (self.view.width - MARGIN * 2 - centerMargin) * 0.5;
        CGFloat item_h = item_w / 170.0 * 228.0;
        layout.itemSize = CGSizeMake(item_w, item_h);
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        layout.minimumLineSpacing = 5;
        layout.minimumInteritemSpacing = 5;
        layout.sectionInset = UIEdgeInsetsMake(0, MARGIN, MARGIN, MARGIN);
        self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        [_collectionView registerClass:[AuctionCollectionViewCell class] forCellWithReuseIdentifier:identifier];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.showsHorizontalScrollIndicator = false;
        _collectionView.backgroundColor = self.view.backgroundColor;
        [self.view addSubview:_collectionView];
    }
    return _collectionView;
}

- (UITextField *)textField {
    if (!_textField) {
        _textField = [[UITextField alloc] init];
        _textField.placeholder = @"请输入您要找的关键字";
        _textField.textColor = SKColorWithHex(0x333333);
        _textField.returnKeyType = UIReturnKeySearch;
        _textField.delegate = self;
        _textField.font = SKFONT_SIZE(16);
    }
    return _textField;
}

#pragma mark -- mark UICollectionViewDelegate UICollectionViewDataSource

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    AuctionCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    SKWeakSelf;
    AuctionSellDataModel *model = self.dataArray[indexPath.item];
    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:model.img] placeholderImage:SKIMAGE_NAMED(@"cell_default_img")];
    cell.title = model.title;
    cell.startPrice = [model.price floatValue];
    cell.status = [model.status intValue];
    cell.sinceEndTimeInterval = model.lost_end_time;
    cell.sinceStartTimeInterval = model.lost_begin_time;
    cell.countDownEndBlock = self.countDownEndBlock;
    [cell shareButtonClickBlock:^{
        [weakSelf cellShareButtonClickWith:indexPath];
    }];
    return cell;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    // 查看商品详情
    AuctionProductDetailVC *vc = [[AuctionProductDetailVC alloc] init];
    AuctionSellDataModel *model = self.dataArray[indexPath.item];
    vc.sellId = model.ID;
    vc.showType = AuctionProductDetailTypeDetail;
    [self dismissViewControllerAnimated:false completion:^{
        [self.viewController.navigationController pushViewController:vc animated:true];
    }];
}

#pragma mark -- mark UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField.text.length > 0) {
        self.searchKey = textField.text;
        [self requestData];
        [self.view endEditing:true];
        return true;
    }
    return false;
}


#pragma mark -- mark 网络数据加载
- (void)requestData {
    _page = 1;
    SKWeakSelf;
    [self requestAuctionRecommandShopDataWith:_page Complete:^(AuctionSellModel *model) {
        weakSelf.dataArray = model.data;
        [weakSelf.collectionView reloadData];
//        if (self->_firstLoad) {
//            [kCountDownManager start];
//            self->_firstLoad = false;
//        }else {
//            [kCountDownManager reload];
//        }
    }];
}
- (void)requstMoreData {
    if (!_page) { [self endRefreshing]; return; } // 还没有下拉刷新呢
    _page += 1;
    SKWeakSelf;
    [self requestAuctionRecommandShopDataWith:_page Complete:^(AuctionSellModel *model) {
        NSMutableArray *mArr = [NSMutableArray arrayWithArray:weakSelf.dataArray];
        [mArr addObjectsFromArray:model.data];
        weakSelf.dataArray = mArr;
        [weakSelf.collectionView reloadData];
        [kCountDownManager reload];
    }];
}


/**
 获取热门推荐数据

 @param page page
 @param complete 回调
 */
- (void)requestAuctionRecommandShopDataWith:(int)page Complete:(void(^)(id))complete {
    if (!self.searchKey) {
        [self showMessage:@"请输入你要找的关键字"];
        [self endRefreshing]; return; }
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param addEntriesFromDictionary:@{@"is_hot":@(0)}];
    [param addEntriesFromDictionary:@{@"page":@(page)}];
    [param addEntriesFromDictionary:@{@"search_key":self.searchKey}];
    SKWeakSelf;
    [YQNetworking getWithUrl:@"Index/getSellList" params:param reloginRefreshBlock:^(id response) {
        [weakSelf endRefreshing];
    } successBlock:^(id response) {
        AuctionSellModel *model = [AuctionSellModel modelWithDictionary:response];
        if ([model isSuccess]) {
            if (complete) {
                complete(model); }
        }else {
            [weakSelf showMessage:model.msg];
        }
        [weakSelf endRefreshing];
    } failBlock:^(NSError *error) {
        [weakSelf endRefreshing];
        [weakSelf debugShowMessage:error.localizedDescription];
    }];
}

- (void)endRefreshing {
    if ([self.collectionView.mj_header isRefreshing]) {
        [self.collectionView.mj_header endRefreshing];
    }
    if ([self.collectionView.mj_footer isRefreshing]) {
        [self.collectionView.mj_footer endRefreshing];
    }
}
#pragma mark -- mark 业务逻辑

/**
 分享商品

 @param indexPath indexPath
 */
- (void)cellShareButtonClickWith:(NSIndexPath *)indexPath {
    
}

#pragma mark -- mark 初始化block
- (void)initBlock {
    SKWeakSelf;
    self.countDownEndBlock = ^{
        [weakSelf requestData]; // 刷新数据
    };
}


#pragma mark -- mark EVENT

/**
 搜索

 @param sender sender
 */
- (void)searchButtonClick:(UIButton *)sender {
    if (self.textField.text.length >0) {
        self.searchKey = self.textField.text;
        [self requestData];
        [self.view endEditing:true];
    }else {
        return;
    }
}

/**
 取消按钮

 @param sender sender
 */
- (void)cancelButtonClick:(UIButton *)sender {
    [self dismissViewControllerAnimated:true completion:nil];
}
@end
